<template>
  <view class="pay">
    <div class="box">
      <div class="box-title">订单金额</div>
      <div>
        ￥<text class="box-amount">{{ amount }}</text>
      </div>

      <div class="btn" @click="payParams">立即支付</div>
    </div>

    <div class="tip">
      <view class="font-weight: bold">若您无法完成微信支付，可以选择：</view>
      <view>① 请他人直接微信扫描下方二维码进行代付。</view>
      <view>② 点击二维码，长摁图片发送给他人完成代付。</view>
    </div>

    <canvas id="qrcode" class="canvas-hide" canvas-id="qrcode" style="width: 300px; height: 300px" />

    <image class="qr-view" style="width: 140px; height: 140px" :src="qrcodeSrc" @click="preview" />

    <div class="btn" @click="payOk">支付完成</div>

    <div class="tip" style="margin-top: 40rpx; text-align: center">代付完成后请点击“支付完成”进入后续流程。</div>
  </view>
</template>

<script>
import uQRCode from '@/components/uqrcode/uqrcode';
import { memberId, baseURL } from '@/common/baseUrl';
import { payQrCodeSign, insurancePay } from '@/api/physicalExamination';
import { getInserviceInfoByOrderId } from '@/api/service';
import { inquiryMixin } from '@/common/mixin.js';
import { tongji } from '@/utils/tools';

export default {
  mixins: [inquiryMixin],

  data() {
    return {
      orderId: '',
      sign: '', // 支付签名
      payLink: 'https://others-pay.wanhuhealth.com/index.html',
      qrcodeSrc: '',
      orderInfo: {},
      packType: [], // 服务包类型：1（保险） 2（体检）
      amount: '0.00', // 金额计算
      insuredId: ''
    };
  },

  computed: {
    // 保险名称
    insuranceName: function () {
      const info = (this.orderInfo.orderProduct || []).find((item) => item.productType === 1 || item.type === 1);
      return info ? info.productName : '';
    }
  },

  onLoad: function (opt) {
    if (opt && opt.orderId) {
      this.orderId = opt.orderId;
      this.init();
    } else {
      uni.showModal({
        content: '参数错误',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            uni.reLaunch({
              url: 'pages/index/index'
            });
          }
        }
      });
    }
  },

  methods: {
    async init() {
      uni.showLoading({
        title: '加载中',
        mask: true
      });
      try {
        const [info, qrcode] = await Promise.all([
          getInserviceInfoByOrderId(this.orderId),
          payQrCodeSign(this.orderId)
        ]);
        // if (info.code !== 0 || qrcode.code !== 0) {
        //   throw new Error();
        // }

        this.orderInfo = info.data;
        this.packType = info.data.orderProduct.map((item) => item.type || item.productType);
        this.amount = (info.data.amount / 100).toFixed(2);
        this.insuredId = info.data.insured.insuredId;

        const text = this.payLink + `?sign=${qrcode.data}&orderNo=${info.data.orderNo}&baseUrl=${baseURL}`;
        this.renderQr(text);
      } catch (error) {
        console.log(error);
        uni.showModal({
          content: '数据请求错误',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              uni.reLaunch({
                url: 'pages/index/index'
              });
            }
          }
        });
      } finally {
        uni.hideLoading();
      }
    },

    // 渲染二维码
    renderQr(text) {
      uQRCode
        .make({
          canvasId: 'qrcode',
          size: 300,
          margin: 10,
          text: text,
          fileType: 'png'
        })
        .then((res) => {
          this.qrcodeSrc = res.tempFilePath;
        });
    },

    // 获取支付参数
    async payParams() {
      uni.showLoading({
        title: '加载中',
        mask: true
      });
      tongji('622bf908-be05-439c-86ef-c4cfdc714d0d');

      try {
        const res = await insurancePay({
          patient_id: wx.getStorageSync('patientid'),
          insurance_order_id: this.orderId,
          params: {
            openId: wx.getStorageSync('openid'), // 微信openId,
            appId: wx.getStorageSync('appid'), // 微信appId
            memberId: memberId,
            channelType: 'W2'
          }
        });
        if (res.code !== 0) throw new Error(res.message || '获取支付参数错误');
        if (res.data.payStatus) {
          uni.showModal({
            title: '该订单已支付,请勿重复支付',
            showCancel: false,
            confirmText: '确定'
          });
          return;
        }
        if (res.data.payInfo) {
          const payInfo = JSON.parse(res.data.payInfo);
          let params = {
            appId: payInfo.appId,
            nonceStr: payInfo.nonceStr,
            package: payInfo.package, // 固定值，以微信支付文档为主
            timeStamp: payInfo.timeStamp,
            paySign: payInfo.paySign,
            signType: payInfo.signType // 根据签名算法生成签名
          };
          this.pay(params);
        }
      } catch (error) {
        console.log(error);
        uni.showModal({
          content: '数据请求错误',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              uni.reLaunch({
                url: 'pages/index/index'
              });
            }
          }
        });
      } finally {
        uni.hideLoading();
      }
    },

    // 调起支付
    pay(params) {
      const self = this;
      uni.requestPayment({
        provider: 'wxpay',
        ...params,
        success: (win) => {
          uni.showLoading({
            title: '支付确认中',
            mask: true
          });
          setTimeout(async () => {
            const res = await getInserviceInfoByOrderId(self.orderId);

            if (res.code !== 0) {
              uni.showModal({
                title: '支付查询错误',
                showCancel: false,
                confirmText: '继续支付'
              });
              return;
            }

            if (res.data.payStatus) {
              self.queryPackageInfo();
            } else {
              uni.showModal({
                title: '服务对象已存在该服务的待支付订单，请前往支付。',
                showCancel: false,
                confirmText: '去支付',
                success: function (res) {
                  if (res.confirm) {
                    uni.reLaunch({
                      url: `pages/service/detail?orderId=${self.orderId}&patientId=${self.insuredId}`
                    });
                  }
                }
              });
              return;
            }
          }, 3000);
        },
        fail: (err) => {
          uni.showModal({
            title: '支付未完成',
            showCancel: false,
            confirmText: '继续支付'
          });
        }
      });
    },

    // 预览二维码
    preview() {
      uni.previewImage({
        current: this.qrcodeSrc,
        urls: [this.qrcodeSrc]
      });
    },

    // 支付完成
    payOk() {
      tongji('192947d0-1eab-4b60-ba03-ea7891f2a8dc');
      const self = this;
      uni.showLoading({
        title: '支付确认中',
        mask: true
      });

      setTimeout(async () => {
        const res = await getInserviceInfoByOrderId(this.orderId);
        if (res.code === 0 && res.data.payStatus) {
          self.queryPackageInfo();
        } else {
          uni.hideLoading();
          uni.showModal({
            title: '支付未完成',
            showCancel: false,
            confirmText: '继续支付'
          });
        }
      }, 3000);
    },

    // 查看服务是否含保险或问询
    async queryPackageInfo() {
      this.inquiryMixin({
        insuranceServices: this.orderInfo.orderProduct,
        teamOrderNo: this.orderInfo.teamOrderNo,
        insuredId: this.insuredId,
        packageId: this.orderInfo.packageId,
        orderId: this.orderId
      });
    }
  }
};
</script>

<style lang="scss" scoped>
@import './../style/common.scss';
.pay {
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
  .box {
    margin: 24rpx;
    background: #ffffff;
    border-radius: 16rpx;
    text-align: center;
    padding: 60rpx 24rpx;

    &-title {
      font-size: 36rpx;
      color: rgba(0, 0, 0, 0.7);
    }

    &-amount {
      font-size: 60rpx;
      padding-right: 4px;
    }
  }
  .btn {
    width: 328rpx;
    border-radius: 44rpx;
    background: linear-gradient(236deg, #fe894d 0%, #ef3931 100%);
    padding: 14rpx 0;
    margin: 40rpx auto 10rpx;
    font-size: 36rpx;
    color: #ffffff;
    text-align: center;
  }

  .tip {
    font-size: 30rpx;
    color: rgba(0, 0, 0, 0.55);
    margin: 80rpx 28rpx 48rpx;
  }
  .qr-view {
    margin: auto;
    display: block;
    margin-bottom: 50rpx;
  }
}
</style>

<style>
.canvas-hide {
  /* 1 */
  position: fixed;
  right: 100vw;
  bottom: 100vh;
  /* 2 */
  z-index: -9999;
  /* 3 */
  opacity: 0;
}
</style>
